package hot100;

public class addTwoNumbers {
    public mergeKLists.ListNode addTwoNumbers(mergeKLists.ListNode l1, mergeKLists.ListNode l2) {
        mergeKLists.ListNode dummy = new mergeKLists.ListNode(0);
        mergeKLists.ListNode cur = dummy;
        int carry = 0;  // 进位值

        // 处理共同长度部分
        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }

            carry = sum / 10;  // 计算新进位
            cur.next = new mergeKLists.ListNode(sum % 10);  // 创建新节点
            cur = cur.next;
        }

        return dummy.next;
    }
}
